package com.security.brows.ui

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.focusable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateMap
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.hub.videobrowsdownload.R
import com.security.brows.room.BrowsWebFavoriteBean
import com.security.brows.values.SecurityBrowsColorsScheme
import com.security.brows.values.SecurityBrowsDrawable

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun ComposeVpPage(
    colorsScheme: SecurityBrowsColorsScheme,
    drawableScheme: SecurityBrowsDrawable,
    favoriteSelect: SnapshotStateMap<String, BrowsWebFavoriteBean>,
    list: State<List<BrowsWebFavoriteBean>>,
    stateFavorite: LazyGridState
) {
    val context = LocalContext.current

    LazyVerticalGrid(
        state = stateFavorite,
        modifier = Modifier.fillMaxSize(),
        columns = GridCells.Adaptive(63.dp),
        contentPadding = PaddingValues(horizontal = 10.dp),
        horizontalArrangement = Arrangement.spacedBy(20.dp),
        verticalArrangement = Arrangement.spacedBy(10.dp)
    ) {
        item(span = { GridItemSpan(maxLineSpan) }) {
            HomeSearchCompose(colorsScheme, context, drawableScheme)
        }
        item(span = { GridItemSpan(maxLineSpan) }) {
            Spacer(modifier = Modifier.height(30.dp))
        }
        items(list.value) {
            Column(
                Modifier
                    .clip(RoundedCornerShape(10.dp))
                    .animateItemPlacement()
                    .width(63.dp)
                    .combinedClickable(interactionSource = remember {
                        MutableInteractionSource()
                    }, indication = rememberRipple(), onLongClick = {
                        if (favoriteSelect.containsKey(it.webUrl)) {
                            favoriteSelect.remove(it.webUrl)
                        } else {
                            favoriteSelect.put(it.webUrl, it)
                        }
                    }) {
                        if (favoriteSelect.isNotEmpty()) {
                            if (favoriteSelect.containsKey(it.webUrl)) {
                                favoriteSelect.remove(it.webUrl)
                            } else {
                                favoriteSelect.put(it.webUrl, it)
                            }
                        } else {
                            SecurityBrowsTabWebActivity.start(context, it.webUrl)
                        }
                    }, horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Spacer(modifier = Modifier.height(5.dp))
                Box(modifier = Modifier.size(52.dp)) {
                    AsyncImage(
                        model = if (it.icon.isNullOrEmpty()) it.iconUrl else it.icon,
                        contentDescription = null,
                        modifier = Modifier
                            .clip(CircleShape)
                            .fillMaxSize(),
                        contentScale = ContentScale.Crop
                    )
                    if (favoriteSelect.containsKey(it.webUrl)) {
                        Image(
                            painter = painterResource(id = R.drawable.brows_select_),
                            contentDescription = null,
                            modifier = Modifier
                                .padding(2.dp)
                                .size(16.dp)
                        )
                    }
                }
                Spacer(modifier = Modifier.height(8.dp))
                val title = it.title
                val showTitle = if (title.isNullOrEmpty()) it.webUrl else it.title
                Text(
                    text = showTitle ?: "",
                    fontSize = 14.sp,
                    color = colorsScheme.historyItemTitle,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                Spacer(modifier = Modifier.height(5.dp))
            }
        }

        item(span = { GridItemSpan(maxLineSpan) }) {
            Image(
                painter = painterResource(id = drawableScheme.how_to_download),
                contentDescription = null,
                modifier = Modifier
                    .padding(top = 30.dp, start = 50.dp, end = 50.dp, bottom = 30.dp)
                    .fillMaxWidth()
                    .clickable(interactionSource = remember {
                        MutableInteractionSource()
                    }, indication = rememberRipple()) {
                        SecurityBrowsGuideActivity.start(context)
                    },
                contentScale = ContentScale.FillWidth
            )
        }

        item(span = { GridItemSpan(maxLineSpan) }) {
            val isUsedPrivacySpace = remember {
                mutableStateOf(context.getSharedPreferences("settings", Context.MODE_PRIVATE).getBoolean("use_external", false))
            }
            Button(
                onClick = {
                    isUsedPrivacySpace.value = !isUsedPrivacySpace.value
                    context.getSharedPreferences("settings", Context.MODE_PRIVATE).edit().putBoolean("use_external", isUsedPrivacySpace.value).apply()
                },
                modifier = Modifier
                    .padding(start = 20.dp, end = 20.dp, bottom = 30.dp)
                    .fillMaxWidth()
            ) {
                Text(if (!isUsedPrivacySpace.value) "Switch storage path to external storage" else "Switch storage path to privacy storage")
            }
        }

    }
}

@Composable
private fun HomeSearchCompose(
    colorsScheme: SecurityBrowsColorsScheme,
    context: Context,
    drawableScheme: SecurityBrowsDrawable
) {
    var searchUrlText1 by remember {
        mutableStateOf("")
    }
    Box(
        modifier = Modifier
            .padding(top = 13.dp, start = 1.dp, end = 6.dp)
            .fillMaxWidth()
            .height(42.dp)

    ) {

        Row(
            Modifier
                .padding(start = 6.dp)
                .fillMaxSize()
                .border(1.dp, colorsScheme.pageSearchBorder, RoundedCornerShape(10.dp))
        ) {
            BasicTextField(
                value = searchUrlText1,
                onValueChange = { searchUrlText1 = it },
                modifier = Modifier
                    .focusable(false)
                    .fillMaxHeight()
                    .weight(1f)
                    .padding(horizontal = 14.dp),
                singleLine = true,
                textStyle = TextStyle(colorsScheme.pageSearchUrl, fontSize = 15.sp),
                keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
                keyboardActions = KeyboardActions(onSearch = {
                    SecurityBrowsTabWebActivity.start(context, searchUrlText1.trim())
                }),
                decorationBox = { innerTextField ->
                    Row(verticalAlignment = Alignment.CenterVertically) {

                        innerTextField()
                    }
                },
                cursorBrush = SolidColor(colorsScheme.cursorBrush)
            )
            Box(modifier = Modifier
                .fillMaxHeight()
                .clickable(interactionSource = remember {
                    MutableInteractionSource()
                }, indication = rememberRipple()) {
                    try {// 获取系统的粘贴板管理器
                        val clipboardManager =
                            context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager

                        // 检查粘贴板是否有内容
                        if (clipboardManager.hasPrimaryClip()) {
                            // 获取粘贴板的内容
                            val clipData: ClipData? = clipboardManager.primaryClip
                            if (clipData != null && clipData.itemCount > 0) {
                                // 获取粘贴板中第一条数据
                                val clipItem = clipData.getItemAt(0)
                                // 获取剪贴板中的文本内容
                                val pasteText = clipItem.text
                                // 使用获取到的文本内容进行后续操作
                                // 例如显示在 TextView 中
                                searchUrlText1 = pasteText
                                    .toString()
                                    .trim()
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }) {
                Image(
                    painter = painterResource(id = drawableScheme.copy),
                    contentDescription = null,
                    modifier = Modifier
                        .padding(end = 10.dp)
                        .align(Alignment.Center)
                        .size(16.dp)
                )
            }
            Box(
                modifier = Modifier
                    .fillMaxHeight()
                    .width(60.dp)
                    .background(
                        colorsScheme.pageSearchActionBg,
                        RoundedCornerShape(topEnd = 10.dp, bottomEnd = 10.dp)
                    )
                    .clickable(interactionSource = remember {
                        MutableInteractionSource()
                    }, indication = rememberRipple()) {
                        SecurityBrowsTabWebActivity.start(context, searchUrlText1.trim())
                    }
            ) {
                Image(
                    painter = painterResource(id = drawableScheme.search),
                    contentDescription = null,
                    modifier = Modifier
                        .align(
                            Alignment.Center
                        )
                        .size(16.dp)
                )
            }
        }

    }
}
